package suncertify.service;

import suncertify.util.Messages;
import suncertify.service.local.LocalServiceImpl;
import suncertify.service.remote.RemoteServiceImpl;

/**
 * Factory pattern implementation for getting Service class implementation
 */
public class ServiceFactory {
    private static final ServiceFactory instance = new ServiceFactory();
    private static final Messages msg = Messages.getInstance();
    private static final String LOCAL_MODE = "local";
    private static final String REMOTE_MODE = "remote";

    public static final String MODE = "suncert.service.mode";

    private Service service;

    private ServiceFactory() {

    }

    /**
     * returns the instance of ServiceFactory
     * @return factory instance
     */
    public static ServiceFactory getInstance() {
        return instance;
    }

    /**
     * returns a implementation of Service
     * @return service
     */
    public Service getService() {
        if (service == null) {
            synchronized (this) {
                if (service == null) {
                    String mode = System.getProperty(MODE);
                    if (mode == null) {
                        throw new IllegalStateException(msg.get("service.mode.null"));
                    } else if (mode.equals(LOCAL_MODE)) {
                        service = new LocalServiceImpl();
                    } else if (mode.equals(REMOTE_MODE)) {
                        service = new RemoteServiceImpl();
                    } else {
                        throw new IllegalStateException(msg.get("service.mode.illegal", mode));
                    }
                }
            }
        }
        return service;
    }
}
